/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.freemarker.method;

import vip.dexian.common.utils.FreeMarkerUtils;
import vip.dexian.common.utils.SpringUtils;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.utility.DeepUnwrap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 消息国际化
 *
 * @author 挺好的 2023年05月30日 15:50
 */
@Component ("messageMethod")
public class MessageMethod implements TemplateMethodModelEx {

    @Override
    @SuppressWarnings ("rawtypes")
    public Object exec (List arguments) throws TemplateModelException {
        String code = FreeMarkerUtils.getArgument(0, String.class, arguments);

        if (StringUtils.isEmpty(code)) {
            return null;
        }

        String message;
        if (arguments.size() > 1) {
            Object[] args = new Object[arguments.size() - 1];
            for (int i = 1; i < arguments.size(); i++) {
                Object argument = arguments.get(i);

                if (argument instanceof TemplateModel templateModel) {
                    args[i - 1] = DeepUnwrap.unwrap(templateModel);
                } else {
                    args[i - 1] = argument;
                }
            }
            message = SpringUtils.getMessage(code, args);
        } else {
            message = SpringUtils.getMessage(code);
        }
        return new SimpleScalar(message);
    }

}
